package com.shujia.wyh;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Scanner;

/*
    登录注册案例
    在数据库创建一张用户信息表  id name passwd create_time status


 */
public class JDBCDemo5 {
    private static Scanner sc = new Scanner(System.in);
    private static Connection conn;
    private static Statement statement;
    private static PreparedStatement preparedStatement;

    public static void main(String[] args) {
        init();

    }

    /**
     * 编写获取数据库操作对象的方法
     */
    public static PreparedStatement getStatement(String sql) {
        try {

            //读取配置文件
            Properties properties = new Properties();
            properties.load(new BufferedReader(new FileReader("mysql/src/main/java/com/shujia/wyh/utils/mysql.properties")));
            //获取数据库的驱动包位置
            String dbVersion = properties.getProperty("dbVersion");
            //获取数据库的连接
            String url = properties.getProperty("url");
            //获取登录数据库的用户名
            String user = properties.getProperty("user");
            //获取登录数据库的密码
            String password = properties.getProperty("password");


            Class.forName(dbVersion);

            conn = DriverManager.getConnection(url, user, password);

            System.out.println("成功与数据库建立连接！！" + conn);

            //获取操作数据库的对象
//            statement = conn.createStatement();
            //创建一个预防sql注入的数据库操作对象
            //先解析sql
            preparedStatement = conn.prepareStatement(sql);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return preparedStatement;
    }

    public static Statement getStatement() {
        try {

            //读取配置文件
            Properties properties = new Properties();
            properties.load(new BufferedReader(new FileReader("mysql/src/main/java/com/shujia/wyh/utils/mysql.properties")));
            //获取数据库的驱动包位置
            String dbVersion = properties.getProperty("dbVersion");
            //获取数据库的连接
            String url = properties.getProperty("url");
            //获取登录数据库的用户名
            String user = properties.getProperty("user");
            //获取登录数据库的密码
            String password = properties.getProperty("password");


            Class.forName(dbVersion);

            conn = DriverManager.getConnection(url, user, password);

            System.out.println("成功与数据库建立连接！！" + conn);

            //获取操作数据库的对象
            statement = conn.createStatement();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return statement;
    }

    public static void login() {
        try {
            Scanner sc = new Scanner(System.in);
            System.out.println("欢迎登录，请先输入您的账户名:");
            String name = sc.nextLine();
            System.out.println("输入您的密码:");
            String passwd = sc.nextLine();

            /**
             *  sql注入的问题：
             *      原因是我们是先做了sql拼接，然后去解析sql的，这样会将sql中的一些特殊单词被解析成sql的语法关键字
             *
             *  解决办法：将先拼接再解析的顺序，调换一下，变成先解析再拼接
             */

            //调用方法获取数据库操作对象
//            Statement statement1 = getStatement();
            //获取的是预编译的数据库操作对象
            String sql = "select name from users where name=? and passwd=?"; // ?相当于一个占位符
            PreparedStatement statement1 = getStatement(sql);
            //再做拼接传值
            statement1.setString(1,name);
            statement1.setString(2,passwd);


//            String sql = "select name from users where name='" + name + "' and passwd='" + passwd + "' ";
//            System.out.println(sql);
            //如果使用了预编译数据库操作对象，在执行查询sql的时候，不需要传入sql值
            ResultSet resultSet = statement1.executeQuery();
            // select name from users where name='qwe' and passwd='qwe' or '1'='1'
            boolean flag = resultSet.next();
            if (flag) {
                System.out.println("===============================");
                System.out.println("登录成功！！！开始您的姻缘......");
                System.out.println("===============================");
            } else {
                System.out.println("登录失败！！请先注册账户");
                System.out.println("是否要进行注册？（Y/N）");
                String c1 = sc.next();
                if ("Y".equals(c1)) {
                    regiest();
                } else {
                    System.out.println("欢迎下次光临！！");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static void regiest() {
        try {
            System.out.println("==============欢迎注册==============");
            System.out.print("请输入您的用户名: ");
            String name = sc.next();
            System.out.print("请输入您的密码: ");
            String password = sc.next();
            // 2023-08-04 15:56:00
            long currentTimeMillis = System.currentTimeMillis();
            Date date = new Date(currentTimeMillis);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(date);


            Statement statement1 = getStatement();
            int flag = statement1.executeUpdate("insert into users(name,passwd,create_time) values('" + name + "','" + password + "','" + time + "')");
            Thread.sleep(3000);
            if (flag == 1) {
                System.out.println("用户注册成功！！");
            } else {
                System.out.println("注册失败！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void delete() {
        try {
            System.out.println("======注销账户=======");
            System.out.print("请输入你要注销的账户：");
            String name = sc.next();
            Statement statement1 = getStatement();
            int flag = statement1.executeUpdate("delete from users where name='" + name + "'");
            System.out.println("后台验证中。。。。。请稍等");
            Thread.sleep(3000);
            if (flag == 1) {

                System.out.println("用户注销成功！！");
            } else {
                System.out.println("注销失败！！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void init() {
        System.out.println("============||欢迎来到刘天保婚姻介绍所||================");
        System.out.println("1. 登录账户");
        System.out.println("2. 注册账户");
        System.out.println("3. 注销账户");
        System.out.println("请选择您要做的操作：[1,2,3]");
        int choice = sc.nextInt();
        switch (choice) {
            case 1:
                login();
                break;
            case 2:
                System.out.println("--------开始注册---------");
                regiest();
                break;
            case 3:
                System.out.println("---------注销账户----------");
                delete();
                break;
            default:
                System.out.println("没有该选项");
                break;
        }


        //关闭连接
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }


}
